package com.ruhua.java.api;

import com.ruhua.java.dao.Category;
import com.ruhua.java.dto.CategoryDTO;
import com.ruhua.java.dto.SuccessDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.service.CategoryService;
import com.ruhua.java.vo.ResVO;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping({"/admin/all_category","/all_category"})
    public ResVO<List> all_category(){
        List<Category> list = categoryService.findAll();
        return ResVO.go(list);
    }

    @GetMapping("/{id}")
    public Category get_category(@PathVariable Long id){
        Category category=categoryService.getById(id);
        if(category == null){
            throw new NotFoundException(10001);
        }
        return category;
    }

    @GetMapping("/name/{name}")
    public Category get_banner_name(@PathVariable String name){
        Optional<Category> optionalCategory=categoryService.getByName(name);
        return optionalCategory.orElseThrow(()-> new NotFoundException(10001));
    }


    @PostMapping("/admin/add_category")
    public ResVO<String> add_category(@RequestBody @Validated CategoryDTO categoryDTO){
        categoryService.createItem(categoryDTO);
        return ResVO.go();
    }

    @PostMapping("/admin/up_category")
    public SuccessDTO up_category(@RequestBody @Validated CategoryDTO categoryDTO){
        categoryService.updateItem(categoryDTO);
        return new SuccessDTO();
    }

    @PutMapping("/admin/del_category")
    public ResVO<String> del_category(@RequestParam Long id){
        categoryService.delItem(id);
        return ResVO.go();
    }


}
